In this article I will explain how to create and render a User Control in ASP.NET MVC.
Create a User Control:
To create a user control you have to add a new item (MVC 3 View User Control (ASPX)) from an Add New Item template. You can change the name of user control as you want. Here I change it as UserControl.ascx.
After adding the user control check whether your user control exists in Shared folder or not and if it not exists in Shared folder then cut the UserControl.ascx from the other locationand paste it into Shared folder.
Here in a UserControl file I simply create a link that call a ShowData() action method from the controller.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%: Html.ActionLink("Home","ShowData",) %>
Create a ShowData action in a Controller that returns a formatted string.
using System.Web.Mvc;
namespace UserControlDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public string ShowData()
{
return "<h3>Page Under Construction</h3>";
}
}
}
After creating a user control you have to render it in your view. Here in an index view I am rendering a User control:
<html>
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
<h3><% Html.RenderPartial("UserControl"); %></h3>
</div>
</body>
</html>
After render a User Control you can see the output as below:
When you click on Home link it will display a message as below:
Thank you for reading this article and I think this will help you a lot.
Munikumar G
01-Nov-2011I need Asp.net menu control working dynamically in app.
Please help me............
Emailid:gulurumunikumar@gmail.com
Munikumar G
01-Nov-2011